﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;

namespace MoneyWentWhere.DataModel.Storage
{
    class NativeXmlFormat : DataFormatX
    {
        public override bool AcceptsFile(string filename)
        {
            // Warning -- not doing any real detection, 
            // encrypted file would pass as normal.
            // TODO: read a bit of a file to figure out the type.
            return Path.GetExtension(filename).Equals(".mww", 
                StringComparison.InvariantCultureIgnoreCase);
        }


        override public void Save(MoneyDataSet ds, Stream outStream)
        {
            DataContractSerializer s = new DataContractSerializer(typeof(MoneyDataSet));

            XmlWriterSettings sett = new XmlWriterSettings();
            sett.Indent = true;

            using (XmlWriter writer = XmlWriter.Create(outStream, sett))
            {
                s.WriteObject(writer, ds);
            }

        }

        override public MoneyDataSet Load(Stream inStream)
        {
            MoneyDataSet ds;
            DataContractSerializer s = GetSerializer();

            using (XmlReader reader = XmlReader.Create(inStream))
            {
                ds = (MoneyDataSet)s.ReadObject(reader, false);
            }

            ds.Accounts.DataSet = ds;
            foreach (Account a in ds.Accounts)
            {
                a.DataSet = ds;
                a.Transactions.Account = a;
                if (a.Guid != Guid.Empty) { ds.StoreObject(a.Guid, this); }
                
                foreach (Transaction tx in a.Transactions)
                {
                    if (tx.Guid != Guid.Empty) { ds.StoreObject(tx.Guid, this); }
                    tx.Account = a;
                }


            }

            return ds;
        }

        static DataContractSerializer GetSerializer()
        {
            Type[] knownTypes = new Type[] { typeof(Account), typeof(Transaction) };
            DataContractSerializer s = new DataContractSerializer(typeof(MoneyDataSet));
            return s;
        }

    }
}
